package com.yuandianrrp.wms;

import com.yuandianrrp.log.jdalog.JpaLogUtils;
import com.yuandianrrp.log.jdalog.utils.SystemUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import javax.swing.*;
import javax.swing.plaf.FontUIResource;
import java.awt.*;
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.Enumeration;

/**
 * @author Administrator
 */
public class SwingUtils {
    public static final String DEFAULT_FONT_NAME = "微软雅黑";
    public static final int DEFAULT_FONT_SIZE = 14;
    public static final int DEFAULT_FONT_STYLE = 0;

    public static Rectangle center(boolean isFullScreen, Integer top, Integer width, Integer height) {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        double screenWidth = screenSize.getWidth();
        double screenHeight = screenSize.getHeight();
        int targetWidth = 0;
        int targetHeight = 0;
        int targetX = 0;
        int targetY = 0;
        if (!isFullScreen) {
            targetWidth = width == null ? (int) (screenWidth * 0.9D) : width.intValue();
            targetHeight = height == null ? (int) (screenHeight * 0.9D) : height.intValue();
            targetX = (int) (screenWidth / 2.0D - targetWidth / 2);
            targetY = top == null ? (int) (screenHeight / 2.0D - targetHeight / 2) :
                    top.intValue();
        } else {
            targetX = 0;
            targetY = 0;
            targetWidth = (int) screenWidth;
            targetHeight = (int) screenHeight - 25;
        }
        return new Rectangle(targetX, targetY, targetWidth, targetHeight);
    }

    public static boolean fileLock() {
        File lockFile = new File(System.getProperty("user.home"), ".weighbridge");
        JpaLogUtils.info("lock file path:" + System.getProperty("user.home"));
        try {
            RandomAccessFile raf = new RandomAccessFile(lockFile, "rw");
            FileChannel chanel = raf.getChannel();
            FileLock lock = chanel.tryLock();
            if (lock != null) {
                return false;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "文件损坏 ，请联系产品供应商！", "警告",
                    2);
            SystemUtils.exit();
        } catch (IOException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "文件损坏，请联系产品供应商！", "警告",
                    2);
            SystemUtils.exit();
        }
        return true;
    }

    public static boolean generateConfigXml(File configXmlFile) {
        try {
            configXmlFile.createNewFile();
            Document initDocument = DocumentHelper.createDocument();


            Element rootElement = initDocument.addElement("config");


            Element server = rootElement.addElement("server");
            server.addAttribute("serverIp", "0.0.0.0");
            server.addAttribute("serverPort", "8080");


            Element serialPort = rootElement.addElement("serialPort");
            serialPort.addAttribute("com", "COM3");
            serialPort.addAttribute("baudRate", "9600");
            serialPort.addAttribute("dataBits", "8");
            serialPort.addAttribute("stopBits", "1");
            serialPort.addAttribute("parity", "0");


            Element weighbridgeNumber = rootElement.addElement("weighbridgeNumber");
            weighbridgeNumber.addAttribute("num", "");


            Element oneSurveillanceCamera = rootElement.addElement("oneSurveillanceCamera");
            oneSurveillanceCamera.addAttribute("oscIP", "192.168.2.210");
            oneSurveillanceCamera.addAttribute("oscProxy", "");
            oneSurveillanceCamera.addAttribute("oscUser", "admin");
            oneSurveillanceCamera.addAttribute("oscPwd", "1111");
            oneSurveillanceCamera.addAttribute("oscPort", "3000");
            oneSurveillanceCamera.addAttribute("oscClientPort", "6000");
            oneSurveillanceCamera.addAttribute("oscChannel", "0");


            Element twoSurveillanceCamera = rootElement.addElement("twoSurveillanceCamera");
            twoSurveillanceCamera.addAttribute("tscIP", "192.168.2.211");
            twoSurveillanceCamera.addAttribute("tscProxy", "");
            twoSurveillanceCamera.addAttribute("tscUser", "admin");
            twoSurveillanceCamera.addAttribute("tscPwd", "1111");
            twoSurveillanceCamera.addAttribute("tscPort", "3000");
            twoSurveillanceCamera.addAttribute("tscClientPort", "6000");
            twoSurveillanceCamera.addAttribute("tscChannel", "0");

            Writer osWrite = new OutputStreamWriter(new FileOutputStream(configXmlFile));

            OutputFormat format = OutputFormat.createPrettyPrint();

            format.setEncoding("UTF-8");

            XMLWriter writer = new XMLWriter(osWrite, format);

            writer.write(initDocument);
            writer.flush();
            writer.close();
            osWrite.close();
        } catch (IOException e) {
            return false;
        }
        return true;
    }

    public static boolean generatePrintConfigXml(File printConfigXmlFile) {
        try {
            printConfigXmlFile.createNewFile();
            Document initDocument = DocumentHelper.createDocument();


            Element rootElement = initDocument.addElement("print");


            Element printer = rootElement.addElement("printer");
            printer.addAttribute("name", "");
            printer.addAttribute("number", "");


            Element mePrint = rootElement.addElement("mePrint");
            mePrint.addAttribute("meScrollPane", "");
            mePrint.addAttribute("meTitle", "");
            mePrint.addAttribute("meSerialNumber", "");
            mePrint.addAttribute("meNumber", "");
            mePrint.addAttribute("meCarCode", "");
            mePrint.addAttribute("meType", "");
            mePrint.addAttribute("meSubweight", "");
            mePrint.addAttribute("meMb", "");
            mePrint.addAttribute("meRp", "");
            mePrint.addAttribute("meOperator", "");
            mePrint.addAttribute("meModifyTime", "");


            Element mlPrint = rootElement.addElement("mlPrint");

            Writer osWrite = new OutputStreamWriter(new FileOutputStream(printConfigXmlFile));

            OutputFormat format = OutputFormat.createPrettyPrint();

            format.setEncoding("UTF-8");

            XMLWriter writer = new XMLWriter(osWrite, format);

            writer.write(initDocument);
            writer.flush();
            writer.close();
            osWrite.close();
        } catch (IOException e) {
            return false;
        }
        return true;
    }

    public static void InitGlobalFont(Font font) {
        FontUIResource fontRes = new FontUIResource(font);
        Enumeration<Object> keys = UIManager.getDefaults().keys();
        while (keys.hasMoreElements()) {
            Object key = keys.nextElement();
            Object value = UIManager.get(key);
            if ((value instanceof FontUIResource)) {
                UIManager.put(key, fontRes);
            }
        }
    }

    public static String addComma(String str) {
        if (str == null) {
            return "";
        }
        String reverseStr = new StringBuilder(str).reverse().toString();
        StringBuilder strTemp = new StringBuilder();
        for (int i = 0; i < reverseStr.length(); i++) {
            if (i * 3 + 3 > reverseStr.length()) {
                strTemp.append(reverseStr.substring(i * 3, reverseStr.length()));
                break;
            }
            strTemp.append(reverseStr.substring(i * 3, i * 3 + 3)).append(",");
        }
        if (strTemp.toString().endsWith(",")) {
            strTemp = new StringBuilder(strTemp.substring(0, strTemp.length() - 1));
        }
        return new StringBuilder(strTemp.toString()).reverse().toString();
    }

    public static int selectedStatisticsValue(JTable table, int column, String errorType) {
        int[] selectedRows = table.getSelectedRows();
        int totalValue = 0;
        for (int selectedRow : selectedRows) {
            Object valueObj = table.getValueAt(selectedRow, column);
            try {
                totalValue += Integer.parseInt(valueObj.toString());
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, errorType + "数据错误！", "错误", 0);
                return -1;
            }
        }
        return totalValue;
    }
}
